package cn.qu.dockman.mgr.disparte;

import cn.qu.dockman.mgr.entity.Container;
import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.entity.Image;
import cn.qu.dockman.mgr.service.ContainerService;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.service.ImageService;
import cn.qu.dockman.protocol.command.client.ContainerListCommand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import static cn.qu.dockman.protocol.command.client.ContainerListCommand.ContainerListBody;

/**
 * Created by zh on 17/3/16.
 */
public class ContainerListObserver implements Observer {

    public ContainerListObserver(DispartMgr dispartMgr) {
        dispartMgr.addObserver(this);
    }

    @Autowired
    private HostService hostService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private ContainerService containerService;

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof ArgDef) {
            ArgDef def = (ArgDef) arg;
            switch (def.getName()) {
                case ContainerListCommand.NAME: {
                    ContainerListBody body = (ContainerListBody) def.getData();

                    Host host = hostService.findByIp(def.getHost());
                    if (host == null) {
                        break;
                    }

                    Image image = imageService.findByHostIdAndImageId(host.getId(), body.getImageId());
                    if (image == null) {
                        break;
                    }

                    Container container = containerService.findContainer(host.getId(), image.getId(), body.getId());
                    if (container == null) {
                        container = new Container();
                        container.setHostId(host.getId());
                        container.setImageId(image.getId());
                        container.setContainerId(body.getId());
                    }
                    container.setCreateTime(new Date(body.getCreated() * 1000));
                    container.setContainerName(StringUtils.join(body.getNames(), ","));
                    container.setContainerStatus(body.getStatus());
                    containerService.saveOrUpdate(container);
                }
                break;
            }
        }
    }
}
